import flash.display.Sprite;
import flash.display.Shape;
import TileModel;
import flash.events.Event;
import flash.geom.Rectangle;

class HealthBarView extends Sprite
{
  public var model:TileModel;
  public var camera:Rectangle;
  private var innerRect:Shape;
  public var Color:Int;
  public function new(inModel:TileModel,inCamera:Rectangle)
  {
    super();
    this.x = 500; this.y=10;
    model = inModel;
    camera = inCamera;
    Color = 0xF722A4;
    model.addEventListener(Event.CHANGE, changeHandler);
    addEventListener(Event.ADDED_TO_STAGE, addedToStagHandler);
  }
  private function addedToStagHandler(event:Event)
  {
    //Draw the object
    draw();
    
    //Add listeners
    addEventListener
      (Event.REMOVED_FROM_STAGE, removedFromStageHandler);
  }

  private function removedFromStageHandler(event:Event)
  {
    removeEventListener
      (Event.ADDED_TO_STAGE, addedToStagHandler);
    removeEventListener
      (Event.REMOVED_FROM_STAGE, removedFromStageHandler);
  }
  
  private function changeHandler(event:Event)
  {
    removeChild(innerRect);
    innerRect = new Shape();
    innerRect.graphics.beginFill(Color);
    innerRect.graphics.drawRect(1, 1, Std.int(50/model.MaxHealth *(model.health)), 5);
    innerRect.graphics.endFill();
    addChild(innerRect);
    this.x = model.xPos-camera.x-2; this.y = model.yPos-camera.y - 15;
  }
  private function draw()
  {
    var outerRect:Shape = new Shape();
    outerRect.graphics.lineStyle(1);
    outerRect.graphics.beginFill(0x000000);
    outerRect.graphics.drawRect(0, 0, 52, 7);
    outerRect.graphics.endFill();

    addChild(outerRect);

    innerRect = new Shape();

    innerRect.graphics.beginFill(Color);
    innerRect.graphics.drawRect(1, 1,  Std.int(50/model.MaxHealth *(model.health)), 5);
    innerRect.graphics.endFill();
    addChild(innerRect);
  }
}